﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Repository;
using RndMaterialDisposalService.Services.Interface.ValidationProblemTracking;
using AutoMapper;
using Masuit.Tools;
using Masuit.Tools.Core.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.POIFS.Crypt.Dsig;

namespace RndMaterialDisposalService.Services.ValidationProblemTracking
{
    /// <summary>
    /// 
    /// </summary>
    [NAutowired]
    public class NewProductApplyService : INewProductApplyService
    {
        private readonly IMapper mapper;
        private readonly ILogger<NewProductApplyService> logger;
        private readonly WorkflowCommonDataContext commonDataContext;
        private readonly AssetsManagementContext assetsManagementContext;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="assetsManagementContext"></param>
        /// <param name="commonDataContext"></param>
        /// <param name="mapper"></param>
        public NewProductApplyService(ILogger<NewProductApplyService> logger, 
            AssetsManagementContext assetsManagementContext, 
            WorkflowCommonDataContext commonDataContext,
            IMapper mapper)
        {
            this.logger = logger;
            this.assetsManagementContext = assetsManagementContext;
            this.commonDataContext = commonDataContext;
            this.mapper = mapper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputReq"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<(List<NewProductApplyReportDto> list, int count)> GetReportData(NewProductApplyReportDataReq inputReq)
        {
            var list = assetsManagementContext.NewProductApplyReport.Where(p => 1 == 1);
            if (!string.IsNullOrEmpty(inputReq.Subject))
            {
                list = list.Where(p => !string.IsNullOrEmpty(p.Subject) && p.Subject.Contains(inputReq.Subject));
            }
            if (!string.IsNullOrEmpty(inputReq.ProcInstId))
            {
                list = list.Where(p => p.ProcInstId == inputReq.ProcInstId);
            }
            if (!string.IsNullOrEmpty(inputReq.Applicant))
            {
                list = list.Where(p => p.Applicant == inputReq.Applicant);
            }
            if (!string.IsNullOrEmpty(inputReq.ProjectName))
            {
                list = list.Where(p => !string.IsNullOrEmpty(p.ProjectName) && p.ProjectName.Contains(inputReq.ProjectName));
            }
            if (!string.IsNullOrEmpty(inputReq.DeptName))
            {
                list = list.Where(p => !string.IsNullOrEmpty(p.DeptName) && p.DeptName.Contains(inputReq.DeptName));
            }
            if (inputReq.StartDate != null && inputReq.EndDate != null)
            {
                list = list.Where(p => p.ApplicantDate >= inputReq.StartDate && p.ApplicantDate < inputReq.EndDate);
            }

            //处理当前节点名称
            var procinstIdList = list.Select(p => $"{p.ProcInstId}".Trim()).ToList();
            var result2 = await commonDataContext.ApplicationData.Where(p => procinstIdList.Contains(p.ProcInstId!.Trim())).ToListAsync();
            list.ForEach(item =>
            {
                var procItem = result2.Where(p => p.ProcInstId!.Trim() == item.ProcInstId!.Trim());
                if (procItem.Any())
                {
                    item.ActivityName = procItem.First().CurrentStatus?.Trim();
                    item.CurrentHandler = procItem.First().CurrentHandler?.Trim();
                }
            });

            var newlist = await list.ToListAsync();
            if (!string.IsNullOrEmpty(inputReq.ActivityName))
            {
                newlist = newlist.Where(p => p.ActivityName == inputReq.ActivityName).ToList();
            }


            //普通用户报表
            if (!string.IsNullOrEmpty(inputReq.CurrentUser))
            {
                var folioList = await commonDataContext.ApplicationApproveData
                    .Where(p => "新产品转中试准备申请表".Equals(p.WorkflowName!.Trim()) && inputReq.CurrentUser == p.ApproverName!.Trim())
                    .Select(p => p.ApplicationNumber!.Trim())
                    .Distinct()
                    .ToListAsync();
                newlist = newlist.Where(p => folioList.Contains(p.Folio!.Trim())).ToList();
            }

            var count = newlist.Count();
            var data = newlist.OrderByDescending(p => p.ApplicantDate)
                .Skip((inputReq.PageIndex - 1) * inputReq.PageSize)
                .Take(inputReq.PageSize).ToList();
            return (data, count);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> SaveReportData(NewProductApplyFormData formData)
        {
            var reportModel = mapper.Map<NewProductApplyReportDto>(formData);
            assetsManagementContext.NewProductApplyReport.AddOrUpdate(p => p.ProcInstId, reportModel);

            var list = await assetsManagementContext.NewProductApplyERPDeviceInfoReport.Where(p => p.ProcInstId == reportModel.ProcInstId).ToListAsync();
            if (list != null && list.Any()) {
                assetsManagementContext.NewProductApplyERPDeviceInfoReport.RemoveRange(list);
            }

            if (formData.ERPDeviceInfo != null && formData.ERPDeviceInfo.Any())
            {
                var deviceList = new List<ERPDeviceInfoReportDto>();
                formData.ERPDeviceInfo.ForEach(p => {
                    var deviceItem = new ERPDeviceInfoReportDto();
                    deviceItem.SysId = Guid.NewGuid();
                    deviceItem.Item = p.IntMod;
                    deviceItem.Description = p.Describe;
                    deviceItem.BatchNum1 = p.BatchNum1;
                    deviceItem.BatchNum2 = p.BatchNum2;
                    deviceItem.BatchNum3 = p.BatchNum3;
                    deviceItem.ProcInstId = reportModel.ProcInstId;
                    deviceItem.CreaterTime = DateTime.Now;
                    deviceList.Add(deviceItem);
                });
                await assetsManagementContext.NewProductApplyERPDeviceInfoReport.AddRangeAsync(deviceList);
            }
            return await assetsManagementContext.SaveChangesAsync();
        }
    }
}
